package com.wjz.admin.config.web;


import com.wjz.commons.entity.bo.AjaxResult;
import com.wjz.commons.enums.ResultCode;
import com.wjz.commons.util.ResultTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * @author wjz
 * @date 2021/1/1 14:33
 * @Description 全局异常处理
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理空指针的异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public AjaxResult exceptionHandler(HttpServletRequest req, HttpServletResponse httpServletResponse, NullPointerException e) {
        log.error("发生空指针异常！原因是:", e);
        httpServletResponse.setStatus(200);
        return ResultTool.fail(new HashMap(2) {{
            put("cause", StringUtils.isEmpty(e.getCause()) ? e.getMessage() : e.getCause().getMessage());
            put("fileName", e.getStackTrace()[0].getFileName());
            put("methodName", e.getStackTrace()[0].getMethodName());
            put("lineNumber", e.getStackTrace()[0].getLineNumber());
            put("type", "空指针异常");
        }}, ResultCode.ABNORMAL_PROGRAM);
    }


    /**
     * 处理其他异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public AjaxResult exceptionHandler(HttpServletRequest req, HttpServletResponse httpServletResponse, Exception e) {
        log.error("未知异常！原因是:", e);
        httpServletResponse.setStatus(200);
        return ResultTool.fail(new HashMap(2) {{
            put("cause", StringUtils.isEmpty(e.getCause()) ? e.getMessage() : e.getCause().getMessage());
            put("fileName", e.getStackTrace()[0].getFileName());
            put("methodName", e.getStackTrace()[0].getMethodName());
            put("lineNumber", e.getStackTrace()[0].getLineNumber());
            put("type", "其他异常");
        }}, ResultCode.ABNORMAL_PROGRAM);
    }
}
